import React, { ReactElement, useState, useEffect, useRef } from 'react';
import { Animated, View } from 'react-native';
import WebView from 'react-native-webview';
import { NavigationScreenProps } from 'react-navigation';
import {
  WebViewNavigationEvent,
  WebViewProgressEvent
} from 'react-native-webview/lib/WebViewTypes';

import styles from './style';
import NavBar from '../../components/NavBar';
import Notch, { NotchType } from '../../components/Notch';
import { getScreenInfo } from '../../util/screen';
import FetchFailed from '../../components/FetchFailed';

const { width } = getScreenInfo({});
export default (props: NavigationScreenProps): ReactElement => {
  const { navigation } = props;
  const title = navigation.getParam('title', '蜜蜂小班');
  const url = navigation.getParam('url');

  const [progress, setProgress] = useState(0);
  const [isFetchFailed, setIsFetchFailed] = useState(false);
  const webView = useRef<WebView>(null);

  const [progressWidth] = useState(new Animated.Value(0));
  const [progressOpacity] = useState(new Animated.Value(1));

  Animated.timing(progressWidth, {
    toValue: progress * width,
    duration: 800
  }).start();

  useEffect((): void => {
    if (progress === 1) {
      setTimeout((): void => {
        Animated.timing(progressOpacity, {
          toValue: 0,
          duration: 400
        }).start();
      }, 500);
    }
  }, [progress]);

  const injectedJavascript = `(function() {
    window.postMessage = function(data) {
      window.ReactNativeWebView.postMessage(data);
    };
  })()`;

  return (
    <Notch style={styles.container} type={NotchType.Top}>
      <NavBar title={title} />
      <Animated.View
        style={[
          styles.progress,
          { width: progressWidth, opacity: progressOpacity }
        ]}
      />
      {isFetchFailed ? (
        <View style={styles.loadFailed}>
          <FetchFailed
            onReload={(): void => {
              setIsFetchFailed(false);
            }}
          />
        </View>
      ) : (
        <WebView
          ref={webView}
          style={styles.webView}
          cacheEnabled
          source={{ uri: url }}
          injectedJavaScript={injectedJavascript}
          onLoadStart={(e: WebViewNavigationEvent): void => {
            // setTitle(e.nativeEvent.title);
          }}
          onLoadEnd={(): void => {}}
          onLoadProgress={(e: WebViewProgressEvent): void => {
            setProgress(e.nativeEvent.progress);
          }}
          onLoad={(): void => {}}
          onError={(e): void => {
            setIsFetchFailed(true);
          }}
        />
      )}
    </Notch>
  );
};
